import React, { useState, useEffect, useMemo } from 'react';
import {
  Drawer,
  Box,
  Typography,
  FormControl,
  FormControlLabel,
  Switch,
  Select,
  MenuItem,
  InputLabel,
  Divider,
  Stack
} from '@mui/material';
import type { SelectChangeEvent } from '@mui/material';
import { useFlowStore } from '../store/flowStore';

interface SettingsPanelProps {
  open: boolean;
  onClose: () => void;
}

/**
 * @function SettingsPanel
 * @description 设置面板组件。用于配置编辑器的各种设置选项。
 * @param {SettingsPanelProps} props - 组件属性，包括是否打开和关闭回调。
 */
const SettingsPanel: React.FC<SettingsPanelProps> = ({ open, onClose }) => {
  // 获取和设置编辑器设置，使用useMemo优化selector
  const settings = useFlowStore(
    useMemo(
      () => (state) => state.settings,
      []
    )
  );
  
  const updateSettings = useFlowStore(state => state.updateSettings);

  // 本地状态用于表单控件
  const [autoSave, setAutoSave] = useState<boolean>(settings.autoSave);
  const [theme, setTheme] = useState<'light' | 'dark'>(settings.theme);
  const [language, setLanguage] = useState<'zh' | 'en'>(settings.language);
  const [showMinimap, setShowMinimap] = useState<boolean>(settings.showMinimap);

  // 当store中的设置变化时，同步更新本地状态
  // 使用深度比较来避免不必要的更新
  useEffect(() => {
    setAutoSave(settings.autoSave);
    setTheme(settings.theme);
    setLanguage(settings.language);
    setShowMinimap(settings.showMinimap);
  }, [settings.autoSave, settings.theme, settings.language, settings.showMinimap]);

  // 处理自动保存开关变化
  const handleAutoSaveChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.checked;
    setAutoSave(newValue);
    updateSettings({ autoSave: newValue });
  };

  // 处理主题选择变化
  const handleThemeChange = (event: SelectChangeEvent) => {
    const newValue = event.target.value as 'light' | 'dark';
    setTheme(newValue);
    updateSettings({ theme: newValue });
  };

  // 处理语言选择变化
  const handleLanguageChange = (event: SelectChangeEvent) => {
    const newValue = event.target.value as 'zh' | 'en';
    setLanguage(newValue);
    updateSettings({ language: newValue });
  };

  // 处理小地图显示开关变化
  const handleMinimapChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.checked;
    setShowMinimap(newValue);
    updateSettings({ showMinimap: newValue });
  };

  if (!open) {
    return null;
  }

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      variant="persistent"
      sx={{
        width: 320,
        flexShrink: 0,
        '& .MuiDrawer-paper': {
          width: 320,
          boxSizing: 'border-box',
          position: 'absolute',
          right: 0,
          top: 64,
          height: 'calc(100% - 64px)',
        },
      }}
    >
      <Box sx={{ p: 2 }}>
        <Typography variant="h6" gutterBottom>
          设置
        </Typography>
        
        <Stack spacing={3} sx={{ mt: 2 }}>
          {/* 编辑器设置 */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              编辑器设置
            </Typography>
            
            <FormControlLabel
              control={
                <Switch
                  checked={autoSave}
                  onChange={handleAutoSaveChange}
                  color="primary"
                />
              }
              label="自动保存"
            />
            
            <Box sx={{ mt: 2 }}>
              <FormControl fullWidth size="small">
                <InputLabel>主题</InputLabel>
                <Select
                  value={theme}
                  label="主题"
                  onChange={handleThemeChange}
                >
                  <MenuItem value="light">浅色</MenuItem>
                  <MenuItem value="dark">深色</MenuItem>
                </Select>
              </FormControl>
            </Box>
            
            <Box sx={{ mt: 2 }}>
              <FormControl fullWidth size="small">
                <InputLabel>语言</InputLabel>
                <Select
                  value={language}
                  label="语言"
                  onChange={handleLanguageChange}
                >
                  <MenuItem value="zh">中文</MenuItem>
                  <MenuItem value="en">English</MenuItem>
                </Select>
              </FormControl>
            </Box>
          </Box>
          
          <Divider />
          
          {/* 显示设置 */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              显示设置
            </Typography>
            
            <FormControlLabel
              control={
                <Switch
                  checked={showMinimap}
                  onChange={handleMinimapChange}
                  color="primary"
                />
              }
              label="显示小地图"
            />
          </Box>
          
          <Divider />
          
          {/* 行为树设置 */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              行为树设置
            </Typography>
            
            <Typography variant="body2" color="text.secondary">
              更多行为树相关设置将在后续版本中添加。
            </Typography>
          </Box>
          
          <Divider />
          
          {/* 快捷键 */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              快捷键
            </Typography>
            
            <Typography variant="body2" component="div">
              <ul style={{ paddingLeft: 20, margin: 0 }}>
                <li>删除节点: Delete/Backspace</li>
                <li>撤销: Ctrl+Z</li>
                <li>重做: Ctrl+Shift+Z</li>
                <li>导出: Ctrl+E</li>
                <li>导入: Ctrl+I</li>
              </ul>
            </Typography>
          </Box>
        </Stack>
      </Box>
    </Drawer>
  );
};

export default SettingsPanel;